package com.suxin.plugin.intergration.manager.finder;

import com.suxin.plugin.FileUtils;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

/**
 * @author Tang
 * @classname ManifestPluginDescriptorFinder
 * @description [  ]
 * @date 2022/7/4 22:00
 */
public class ManifestPluginDescriptorFinder implements PluginDescriptorFinder{

    @Override
    public boolean isApplicable(Path pluginPath) {
        return Files.exists(pluginPath) && (Files.isDirectory(pluginPath));
    }

    @Override
    public PluginDescriptor find(Path pluginPath) {
        Manifest manifest = readManifest(pluginPath);
        return createPluginDescriptor(manifest);
    }

    private PluginDescriptor createPluginDescriptor(Manifest manifest) {
        DefaultPluginDescriptor defaultPluginDescriptor = new DefaultPluginDescriptor();

        return defaultPluginDescriptor;
    }

    private Manifest readManifest(Path pluginPath) {
        if (FileUtils.isJarFile(pluginPath)) {
            try(JarFile jarFile = new JarFile(pluginPath.toFile())) {
                return jarFile.getManifest();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Path path = getManifestPath(pluginPath);
        if (path != null) {
            try (InputStream inputStream = Files.newInputStream(path)) {
                return new Manifest(inputStream);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private Path getManifestPath(Path pluginPath) {
        return FileUtils.findFile(pluginPath, "MANIFEST.MF");
    }
}